class Item < ActiveRecord::Base

  alias_attribute :row, :location_row
  alias_attribute :column, :location_column
  alias_attribute :foregroundColor, :foreground_color
  alias_attribute :backgroundColor, :background_color
  alias_attribute :isHighlighted, :is_highlighted

  composed_of :location, :mapping => [ %w(location_row row), %w(location_column column) ], :converter => :adapt

  belongs_to :grid

  def self.find_top(grid_id, location)
    max_order = self.maximum(:order, :conditions =>
        ['grid_id=? AND location_row=? AND location_column=?', grid_id, location[:row], location[:column]])
    self.find(:first, :conditions =>
        ['grid_id=? AND location_row=? AND location_column=? AND `order`=?', grid_id, location[:row], location[:column], max_order])
  end

  def self.find_stack(grid_id, location)
    self.find(:all, :conditions => ['grid_id=? AND location_row=? AND location_column=?', grid_id, location[:row], location[:column]], :order => '`order` DESC')
  end

  def self.exists_at_location?(grid_id, location)
    self.exists?(['grid_id=? AND location_row=? AND location_column=?', grid_id, location[:row], location[:row]])
  end

  def self.move_stack(grid_id, old_location, new_location)
    stack = self.find_stack(grid_id, old_location)
    if (self.exists_at_location?(grid_id, new_location))
      top_order = self.find_top(grid_id, new_location).order
      stack.each do |item|
        item.update_attributes!(
          :location => Location.adapt(new_location),
          :order => (top_order = top_order + 1))
      end
    else
      stack.each do |item|
        item.update_attributes!(:location => Location.adapt(new_location))
      end
    end
  end

  def self.set_top_item(grid_id, location, order)
    stack = Item.find_stack(grid_id, location)
    to_remove = stack.find {|item| item.order == order}
    stack.delete(to_remove)
    stack.push(to_remove)
    stack.each_index do |index|
      item = stack[index]
      item.update_attributes!(:order => index + 1)
    end
  end

  def self.destroy_at_dimensions(rows, columns)
    self.destroy_all(['location_row >= ? OR location_column >= ?', rows, columns])
  end

  def to_hash
    ToHash.eval_attributes(self, [:order, :foregroundColor, :backgroundColor, :location, :text, :isHighlighted])
  end

end
